//
//  FKGoodsListVC.m
//  WanTao
//
//  Created by Macbook Pro on 2019/3/13.
//  Copyright © 2019 Macbook Pro. All rights reserved.
//

#import "FKGoodsListVC.h"
#import "FKGoodsFilterView.h"
#import "FKGoodsListCell.h"
#import "FKAreaAndTradeView.h"
#import "FKHomeGoods.h"
//#import "FKArea.h"
#import "FKTrade.h"
#import "FKCommodityDetailVC.h"
#import "FKSearchVC.h"


@interface FKGoodsListVC ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, strong) NSArray *datas;
@property(nonatomic, assign) NSInteger page;
@property (nonatomic, strong) UIView *emptyView;

@property (nonatomic, weak) FKGoodsFilterView *filterView;
//@property (nonatomic, strong) NSArray *cateList;
//@property (nonatomic, strong) NSArray *ageRange;

@end

@implementation FKGoodsListVC

- (NSArray *)datas
{
    if (!_datas) {
        _datas = [NSArray array];
    }
    return _datas;
}

- (NSMutableDictionary *)param
{
    if (!_param) {
        _param = [NSMutableDictionary dictionary];
        _param[@"pagesize"] = @(10);
    }
    return _param;
}

- (UIView *)emptyView
{
    if (!_emptyView) {
        _emptyView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, 200)];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Emptyorder"]];
        [_emptyView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.offset(0);
            make.width.mas_equalTo(fk_adjustW(imageView.image.size.width));
            make.height.mas_equalTo(fk_adjustW(imageView.image.size.height));
        }];
        
        UILabel *label = [[UILabel alloc] init];
        [_emptyView addSubview:label];
        label.font = fk_adjustFont(16);
        label.text = @"暂无数据!";
        label.textColor = fkColor999999;
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(imageView.mas_bottom).offset(20);
            make.centerX.offset(0);
        }];
    }
    return _emptyView;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (self.filterView) {
        if (self.filterView.cateList.count > 0) {
            [self.filterView updateSelectedCate];
        } else {
            FKLog(@"分类数据加载失败");
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    UITableView *tableView = [[UITableView alloc] init];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
//    UIView *searchView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, fk_adjustW(50))];
//    [self.view addSubview:searchView];
//    searchView.backgroundColor = fkBgColor;
//
//    UIButton *searchBtn = [UIButton fk_btnWithTarget:self action:@selector(searchBtnClicked) font:fk_adjustFont(13) normalTitle:@"请输入关键词搜索" normalTitleColor:fkColor999999 selectedTitle:nil selectedTitleColor:nil normalImg:[UIImage imageNamed:@"nav_search"] selectedImg:nil bgImg:nil selectedBgImg:nil];
//    [searchView addSubview:searchBtn];
//    searchBtn.backgroundColor = fkColorECECEC;
//    [searchBtn fk_viewCornerRadius:fk_adjustW(15) borderWidth:0 borderColor:nil];
//    searchBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//    searchBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 12, 0, 0);
//    searchBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
//    CGFloat searchBtnH = fk_adjustW(30);
//    CGFloat searchBtnY = (searchView.fk_height - searchBtnH) * 0.5;
//    searchBtn.frame = CGRectMake(15, searchBtnY, fkScreenW - 30, searchBtnH);

    FKGoodsFilterView *filterView = [[FKGoodsFilterView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, fk_adjustW(45))];
    [self.view addSubview:filterView];
    self.filterView = filterView;
    fkWeakSelf(self);
    filterView.updateFilterBlock = ^(NSDictionary * _Nonnull param) {
        [weakself.param addEntriesFromDictionary:param];
        [weakself loadData];
    };
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.top.equalTo(filterView.mas_bottom);
    }];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView.mj_header beginRefreshing];
    
    [self loadArea];
    [self loadCateList];
    [self loadAgeRange];
    
    if ([FKCacheTool storeId]) {
        self.param[@"store_id"] = [FKCacheTool storeId];
    }
}

- (void)searchBtnClicked
{
    FKSearchVC *vc = [[FKSearchVC alloc] init];
    fkPushNav(vc);
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    FKGoodsListCell *cell = [FKGoodsListCell cellWith:tableView];
    cell.data = self.datas[indexPath.row];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return fk_adjustW(140);
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FKCommodityDetailVC *vc = [[FKCommodityDetailVC alloc] init];
    FKHomeGoods *model = self.datas[indexPath.row];
    vc.itemId = model.id;
    fkPushNav(vc);
}

#pragma mark - 网络请求
- (void)loadArea
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"area_id"] = [FKCacheTool storeId];
    [FKHttpTool postWithSuffix:@"m=Home&c=Index&a=areaList" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            
            CGFloat headerH = 0;
            NSMutableDictionary *data = [NSMutableDictionary dictionary];
            NSArray *areas = result.data[@"list"];
            CGFloat itemH = fk_adjustW(20);
            if (areas.count > 0) {
                CGFloat itemW = (fkScreenW - fk_adjustW(58) - 5 * 3 - 12) / 4.f;
                NSMutableArray *items = [NSMutableArray array];
                for (NSDictionary *area in areas) {
                    NSMutableDictionary *areaItem = [NSMutableDictionary dictionary];
                    [items addObject:areaItem];
                    areaItem[@"cellName"] = @"FKAreaItemCell";
                    areaItem[@"data"] = area;
                    areaItem[@"itemSize"] = @(CGSizeMake(itemW, itemH));
                }
                data[@"areas"] = items;
                
                NSInteger rows = areas.count % 4 == 0 ? areas.count / 4 : areas.count / 4 + 1;
                headerH = fk_adjustW(12) + rows * itemH + (rows - 1) * 5 + fk_adjustW(15);
            }
            data[@"areaH"] = @(headerH);
            
            NSArray *trades = [FKTrade mj_objectArrayWithKeyValuesArray:result.data[@"trade"]];
            
            if (trades.count > 0) {
                CGFloat titleW = [@"热门商圈:" sizeWithAttributes:@{NSFontAttributeName : fk_adjustFont(14)}].width + fk_adjustW(10);
                CGFloat beginX = 12 + titleW + 5;
                CGFloat itemX = 0;
                CGFloat itemY = 0;
                CGFloat itemRight = 0;
                for (FKTrade *trade in trades) {
                    CGFloat itemW = [trade.name sizeWithAttributes:@{NSFontAttributeName : fk_adjustFont(14)}].width + fk_adjustW(14);
                    
                    NSInteger index = [trades indexOfObject:trade];
                    if (index == 0) {
                        itemX = beginX;
                    }
                    
                    itemRight = (itemX + itemW);
                    if (itemRight > fkScreenW - 12) {
                        itemX = 12;
                        itemRight = itemX;
                        itemY += (itemH + 5);
                        headerH += (itemH + 5);
                    }
                    trade.itemFrame = CGRectMake(itemX, itemY, itemW, itemH);
                    itemX += (itemW + 5);
                    
                    if ([trade isEqual:trades.firstObject]) {
                        headerH += itemH;
                    }
                }
                data[@"trades"] = trades;
                headerH += fk_adjustW(10);
            }
            data[@"headerH"] = @(headerH);
            
            FKAreaAndTradeView *header = [[FKAreaAndTradeView alloc] initWithFrame:CGRectMake(0, 0, fkScreenW, headerH)];
            self.tableView.tableHeaderView = header;
            header.data = data;
            fkWeakSelf(self);
            header.didSelectedArea = ^(NSDictionary * _Nonnull param) {
                [weakself.param addEntriesFromDictionary:param];
                [weakself loadData];
                [weakself loadTrades:param[@"area_id"]];
            };
            header.didSelectedTrade = ^(NSDictionary * _Nonnull param) {
                [weakself.param addEntriesFromDictionary:param];
                [weakself loadData];
            };
        }
    } failure:nil];
}

- (void)dealData
{
    
}

/** 刷新头部商圈数据 */
- (void)loadTrades:(NSString *)region_id
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"area_id"] = @"20";
    param[@"region_id"] = region_id;
    [FKHttpTool postWithSuffix:@"m=Home&c=Index&a=areaList" param:param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            if (self.tableView.tableHeaderView) {
                FKAreaAndTradeView *header = (FKAreaAndTradeView *)self.tableView.tableHeaderView;
                
                NSArray *trades = [FKTrade mj_objectArrayWithKeyValuesArray:result.data[@"trade"]];
                CGFloat tradeH = 0;
                if (trades.count > 0) {
                    CGFloat titleW = [@"热门商圈:" sizeWithAttributes:@{NSFontAttributeName : fk_adjustFont(14)}].width + fk_adjustW(10);
                    CGFloat beginX = 12 + titleW + 5;
                    CGFloat itemX = 0;
                    CGFloat itemY = 0;
                    CGFloat itemRight = 0;
                    CGFloat itemH = fk_adjustW(20);
                    for (FKTrade *trade in trades) {
                        CGFloat itemW = [trade.name sizeWithAttributes:@{NSFontAttributeName : fk_adjustFont(14)}].width + fk_adjustW(14);
                        
                        NSInteger index = [trades indexOfObject:trade];
                        if (index == 0) {
                            itemX = beginX;
                        }
                        
                        itemRight = (itemX + itemW);
                        if (itemRight > fkScreenW - 12) {
                            itemX = 12;
                            itemRight = itemX;
                            itemY += (itemH + 5);
                            tradeH += (itemH + 5);
                        }
                        trade.itemFrame = CGRectMake(itemX, itemY, itemW, itemH);
                        itemX += (itemW + 5);
                        
                        if ([trade isEqual:trades.firstObject]) {
                            tradeH += itemH;
                        }
                    }
                    tradeH += fk_adjustW(10);
                }
                
                [header updateTrades:trades tradeH:tradeH];
                self.tableView.tableHeaderView = header;
            }
        }
    } failure:nil];
}

- (void)search
{
    [self loadData];
}

- (void)loadData
{
    self.page = 1;
    self.param[@"page"] = @(self.page);
    [FKHttpTool postWithSuffix:@"m=Home&c=Index&a=itemList" param:self.param success:^(FKBaseResult *result) {
        [self.tableView.mj_header endRefreshing];
        if (result.isSuccess) {
            self.datas = [FKHomeGoods mj_objectArrayWithKeyValuesArray:result.data[@"list"]];
            [self.tableView reloadData];
            if (self.datas.count > 0) self.page++;
        }
        [self.tableView fk_tableViewCheckEmptyDataWithDataCount:self.datas.count emptyView:self.emptyView];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView fk_tableViewCheckEmptyDataWithDataCount:self.datas.count emptyView:self.emptyView];
    }];
}

- (void)loadMoreData
{
    self.param[@"page"] = @(self.page);
    [FKHttpTool postWithSuffix:@"m=Home&c=Index&a=itemList" param:self.param success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            NSArray *newArray = [FKHomeGoods mj_objectArrayWithKeyValuesArray:result.data[@"list"]];
            if (newArray.count > 0) {
                NSMutableArray *array = [NSMutableArray arrayWithArray:self.datas];
                [array addObjectsFromArray:newArray];
                self.datas = array;
                [self.tableView reloadData];
                self.page++;
                [self.tableView.mj_footer endRefreshing];
            } else {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
    } failure:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (void)loadCateList
{
    [FKHttpTool postWithSuffix:@"m=Home&c=Index&a=cateList" param:nil success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            self.filterView.cateList = result.data[@"cate"];
        }
    } failure:nil];
}

- (void)loadAgeRange
{
    [FKHttpTool postWithSuffix:@"m=Home&c=Index&a=age_range" param:nil success:^(FKBaseResult *result) {
        if (result.isSuccess) {
            self.filterView.ageRange = result.data[@"age_range"];
        }
    } failure:nil];
}


@end
